package com.blog.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.bo.BlogManagerBO;
import com.blog.entity.BlogManager;
import com.blog.enums.DataStatusEnum;
import com.blog.service.ManagerService;
import com.blog.utils.BusinessException;
import com.blog.utils.ConstUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author Huangzp
 * @Date 2022/1/10 14:50
 */
@Slf4j
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private BlogManagerBO blogManagerBO;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public List<BlogManager> getManagerByPage(BlogManager manager) {
        BlogManager manager1 = (BlogManager) SecurityUtils.getSubject().getPrincipal();
        if (manager1.getType().equals(ConstUtil.SUPER_ADMIN)) {
            manager.setType(ConstUtil.ADMIN);
        }
        if (manager1.getType().equals(ConstUtil.ADMIN)) {
            manager.setType(ConstUtil.BOLG_MIN);
        }

        QueryWrapper<BlogManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtils.isNotBlank(manager.getUsername()), BlogManager::getUsername, manager.getUsername())
                .like(StringUtils.isNotBlank(manager.getName()), BlogManager::getName, manager.getName())
                .eq(StringUtils.isNotBlank(manager.getType()), BlogManager::getType, manager.getType())
                .orderByDesc(BlogManager::getCreateTime)
                .orderByDesc(BlogManager::getStatus);
        return blogManagerBO.list(queryWrapper);
    }

    @Override
    public void delManager(List<Integer> ids) throws BusinessException{
        try {
            blogManagerBO.removeByIds(ids);
        }catch (BusinessException e){
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public void stopManager(List<Integer> ids, int key) throws BusinessException{
        try {
            List<BlogManager> managers = blogManagerBO.listByIds(ids);
            if(managers.stream().anyMatch(x->x.getStatus()==key)){
                throw new BusinessException("已经是"+ DataStatusEnum.getValue(key)+"状态");
            }
            managers.forEach(x->x.setStatus(key));
            blogManagerBO.updateBatchById(managers);
        }catch (BusinessException e){
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public BlogManager saveManager(BlogManager manager) throws BusinessException {
        try {
            if (manager.getId()==null){
                manager.setCreateTime(new Date());
            }

            //先验证邮箱是否已经被注册
            BlogManager byName = this.findByName(manager.getUsername());
            if (byName != null){
                throw new BusinessException("已经注册，不能再次注册。");
            }

            if(manager.getCode()!=null){
                String codes = (String) request.getSession().getAttribute("code");
                if (codes == null){
                    throw new BusinessException("验证码已经失效。");
                }

                int code = Integer.parseInt(codes);
                if(manager.getCode() != code){
                    throw new BusinessException("验证码输入错误。");
                }
            }


            manager.setPassword(SecureUtil.md5(manager.getPassword()));
            blogManagerBO.save(manager);
            return manager;
        } catch (BusinessException e) {
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public BlogManager findByName(String userName) throws BusinessException {
        //通过用户名查询
        QueryWrapper<BlogManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BlogManager::getUsername,userName)
                .eq(BlogManager::getStatus,ConstUtil.DEFAULT_STATE);
        return  blogManagerBO.getOne(queryWrapper);
    }

    @Override
    public BlogManager updateManager(BlogManager manager) {
        QueryWrapper<BlogManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(BlogManager::getId,manager.getId())
                .eq(BlogManager::getUsername,manager.getUsername())
                .eq(BlogManager::getStatus, ConstUtil.DEFAULT_STATE);

        if (blogManagerBO.count(queryWrapper)>0){
            throw new BusinessException("用户名或者昵称已经存在");
        }

        if (manager.getPassword()!=null){
            manager.setPassword(SecureUtil.md5(manager.getPassword()));
        }

        blogManagerBO.updateById(manager);
        return manager;
    }

    @Override
    public void sendOutEmail(String username)  throws BusinessException{
        try {
            //先验证邮箱是否已经被注册
            BlogManager byName = this.findByName(username);
            if (byName != null){
                throw new BusinessException("邮箱已经注册，不能再次注册。");
            }

            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("610331423@qq.com");
            helper.setTo(username);
            helper.setSubject("标题：请收好你在风的博客的注册码");

            String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
            HttpSession session = request.getSession();
            session.setAttribute("code", checkCode);

            String str ="<h4>欢迎您在风的博客注册</h4>"+"<p style='color:#F00'>您的验证码为:"+checkCode+"</p>";
            //append("<p style='text-align:right'>右对齐</p>");
            helper.setText(str, true);

       /* FileSystemResource fileSystemResource=new FileSystemResource(new File("C:\\Users\\28937\\Desktop\\搞笑图片\\welcome.gif"));
        helper.addAttachment("啦啦啦",fileSystemResource);*/
            javaMailSender.send(message);
        } catch (BusinessException e) {
            throw new BusinessException(e.getErrorMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
